package com.yuntongxun.ecdemo.voicechat.ui.services;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.storage.GroupSqlManager;
import com.yuntongxun.ecdemo.storage.IMessageSqlManager;
import com.yuntongxun.ecdemo.ui.CCPFragment;
import com.yuntongxun.ecdemo.ui.group.GroupService;
import com.yuntongxun.ecdemo.voicechat.bean.PostResult;
import com.yuntongxun.ecdemo.voicechat.comman.EventBusTags;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.im.ECGroup;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by zhuonan on 2016/12/16.
 */

public class DiscussionService extends Service implements
        GroupService.Callback{
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

//    private boolean sync = false;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        registerReceiver(new String[]{
                "DiscussionService.inited",
                IMessageSqlManager.ACTION_GROUP_DEL});

//        if (!sync) {
            LogUtil.e("service_start","start");
            GroupService.syncGroup(this);
            GroupService.syncDiscussionGroup(this);
//            sync = true;
//        }
        return super.onStartCommand(intent, flags, startId);
    }

    InternalReceiver internalReceiver;
    /**
     * 注册广播Action，子类如果需要监听广播可以调用
     * 该方法传入相应事件的Action
     * @param actionArray
     */
    protected final void registerReceiver(String[] actionArray) {
        if (actionArray == null) {
            return;
        }
        IntentFilter intentfilter = new IntentFilter();
        for (String action : actionArray) {
            intentfilter.addAction(action);
        }
        //intentfilter.addAction(CASIntent.ACTION_SERVICE_DESTORY);
        //intentfilter.addAction(CASIntent.ACTION_FORCE_DEACTIVE);
        if (internalReceiver == null) {
            internalReceiver = new InternalReceiver();
        }
        registerReceiver(internalReceiver, intentfilter);
    }

    private class InternalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent == null || intent.getAction() == null) {
                return ;
            }
            handleReceiver(context, intent);
        }

    }

    protected void handleReceiver(Context context, Intent intent) {
        if (intent.getAction().equals(
                new String[]{"DiscussionService.inited"})) {
            GroupService.syncGroup(this);
        } else if (IMessageSqlManager.ACTION_GROUP_DEL.equals(intent
                .getAction())) {
            onSyncGroup();
        }
    }
    @Override
    public void onSyncGroup() {
        Cursor cursor = GroupSqlManager.getGroupCursor(false);
        List<ECGroup> ecGroups=new ArrayList<>();
        try {
            if (cursor != null) {
                while(cursor.moveToNext()){
                    ECGroup ecGroup=new ECGroup();
                    ecGroup.setGroupId(cursor.getString(0));
                    ecGroup.setName(cursor.getString(1));
                    ecGroup.setGroupType(cursor.getInt(2));
                    ecGroup.setCount(cursor.getInt(3));
                    ecGroup.setPermission(ECGroup.Permission.values()[cursor.getInt(4)]);
                    ecGroups.add(ecGroup);
                }

            }
        }catch (Exception e){
            LogUtil.e("e",e.toString());
        }finally {
            cursor.close();
        }
//        LogUtil.e("size__",ecGroups.size()+"");
//        for (int i=0;i<ecGroups.size();i++){
//            LogUtil.e("disscus",ecGroups.get(i).getName());
//        }
//        GroupService.syncGroup(this);
//        List<ECGroup> mArrayList = GroupSqlManager.getJoinGroups();
//        LogUtil.e("group_size",mArrayList.size()+"");
//        for (int i=0;i<mArrayList.size();i++){
//            LogUtil.e("group",mArrayList.get(i).getName());
//        }

        PostResult postResult = new PostResult();
        postResult.setTag(EventBusTags.REGISTER_FINISH);
        EventBus.getDefault().post(postResult);
    }

    @Override
    public void onSyncGroupInfo(String groupId) {

    }

    @Override
    public void onGroupDel(String groupId) {

    }

    @Override
    public void onError(ECError error) {

    }

    @Override
    public void onUpdateGroupAnonymitySuccess(String groupId, boolean isAnonymity) {

    }
}
